package com.xncoding.netty.socket.my.nio.demo01;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class NioClientHander extends Thread {

    private Selector selector;
    private Charset charset;
    public NioClientHander(Selector selector, Charset charset) {
        this.selector = selector;
        this.charset = charset;
    }
    @Override
    public void run() {
        while (true) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectedKeys.iterator();
                SelectionKey key = null;
                while (it.hasNext()) {
                    key = it.next();
                    it.remove();
                    if (!key.isValid()){
                        continue;
                    }
                    dispatch(key);
                }
            } catch (Exception ignore) {
            }
        }
    }
    private void dispatch(SelectionKey key) throws IOException {
        if (key.isAcceptable()) {
            send(key);
        }else if (key.isReadable()) {
            read(key);
        }
    }

    private void send(SelectionKey key) throws IOException {
        SocketChannel socketChannelKey = (SocketChannel) key.channel();
        if (socketChannelKey.finishConnect()) {
            socketChannelKey.register(selector, SelectionKey.OP_READ);
            byte[] req = "这是客户端发送的消息".getBytes();
            ByteBuffer byteBuffer = ByteBuffer.allocate(req.length);
            byteBuffer.put(req);
            byteBuffer.flip();
            socketChannelKey.write(byteBuffer);
            if (!byteBuffer.hasRemaining()) {
                System.out.println("客户端发送消息成功");
            }
        } else {
            System.exit(1);
        }
    }

    private void read(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        int readBytes = socketChannel.read(readBuffer);
        if (readBytes > 0) {
            readBuffer.flip();
            byte[] bytes = new byte[readBuffer.remaining()];
            readBuffer.get(bytes);
            String body = new String(bytes, "utf-8");
            System.out.println("服务端回复： " + body);
        } else if (readBytes < 0) {
            key.cancel();
            socketChannel.close();
        } else {
            System.exit(1);
        }
    }


}
